<template>
	<div
		class="group inline-block relative"
		ref="select"
		@mouseleave="show = false"
	>
		<div
			class="text-sm border flex items-center rounded h-9 whitespace-nowrap cursor-pointer min-w-24"
			@click="show = true"
			ref="titleBox"
		>
			<div class="flex-1 pl-2">{{ topname }}</div>
			<template v-if="modelValue">
				<i
					v-if="clearable"
					class="ri-close-circle-fill duration-300 mr-2 hover:text-hong-300"
					@click.stop="removeId"
				></i>
			</template>
			<template v-else>
				<i
					class="ri-arrow-down-s-line duration-300 mr-2"
					:class="{ '-rotate-180': show }"
				></i>
			</template>
		</div>
		<div
			class="overflow-hidden duration-300 max-h-0 flex flex-col text-gray-800 bg-white rounded-sm absolute z-30 min-w-24"
			ref="optionsNode"
			:class="{ 'max-h-[300px] overflow-y-auto': show }"
		>
			<ypmenu
				v-model="chitem"
				:dataList="itemList"
				:value="modelValue"
				ref="ypmenu_dom"
			></ypmenu>
		</div>
	</div>
</template>
<script setup>
	import { ref, onMounted, watch, nextTick } from 'vue'
	const props = defineProps({
		modelValue: '',
		itemList: Object,
		clearable: {
			type: Boolean,
			default: true
		},
		col: {
			default: [],
		},
		defaultTitle: {
			default: '--请选择--',
		},
	})
	const emit = defineEmits(['update:modelValue'])
	const chitem = ref('')
	const show = ref(false) //是否显示菜单
	const topname = ref(props.defaultTitle) //选取的标题
	const titleBox = ref(null)
	const select = ref(null)
	const optionsNode = ref(null)
	const ypmenu_dom = ref(null)
	const getAttr = () => {
		let timegetw = setInterval(() => {
			if (optionsNode.value && optionsNode.value.clientWidth) {
				let minw = 120
				if (optionsNode.value.clientWidth >= minw) {
					minw = optionsNode.value.clientWidth
				}
				titleBox.value.style.width = minw + 'px'
				optionsNode.value.style.width = minw + 'px'
				clearInterval(timegetw)
			}
		}, 10)
	}

	watch(chitem, (newVal, oldVal) => {
		if (newVal) {
			topname.value = newVal.title
			emit('update:modelValue', newVal.id + '')
			show.value = false
		}
	})
	watch(
		() => props.itemList,
		(n) => {
			topname.value = props.defaultTitle
		}
	)
	watch(
		() => props.modelValue,
		(n) => {
			if (!n){
        topname.value = props.defaultTitle
        chitem.value = ''
      } 
		}
	)

	const removeId = () => {
		topname.value = props.defaultTitle
		chitem.value = ''
		emit('update:modelValue', null)
	}
	onMounted(() => {
		if (props.itemList) {
			props.itemList.forEach((item) => {
				if (item.id == props.modelValue) {
					topname.value = item.title
				}
			})
		}
		// getAttr()
	})
</script>
